<template>
  <div class="app-container">
    <div class="filter-container">
      <el-card shadow="hover">
        <el-form :inline="true" :model="queryParams" ref="queryForm" size="small">
          <el-form-item label="城市" prop="city">
            <el-input v-model="queryParams.city" placeholder="请输入城市" clearable style="width: 200px" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item label="排名范围" prop="rankingRange">
            <el-select v-model="queryParams.rankingRange" placeholder="排名范围" clearable style="width: 200px">
              <el-option v-for="item in rankingOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <el-row :gutter="20">
      <!-- 统计卡片 -->
      <el-col :span="24">
        <el-card shadow="hover" class="statistics-card">
          <div slot="header" class="card-header">
            <span><i class="el-icon-data-analysis"></i> 高校数据概览</span>
          </div>
          <el-row :gutter="20">
            <el-col :sm="12" :md="6">
              <div class="stat-item">
                <div class="stat-icon" style="background-color: #409EFF">
                  <i class="el-icon-school"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-title">高校总数</div>
                  <div class="stat-value">{{ statisticsData.totalCount }}</div>
                </div>
              </div>
            </el-col>
            <el-col :sm="12" :md="6">
              <div class="stat-item">
                <div class="stat-icon" style="background-color: #67C23A">
                  <i class="el-icon-position"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-title">覆盖城市</div>
                  <div class="stat-value">{{ statisticsData.cityCount }}</div>
                </div>
              </div>
            </el-col>
            <el-col :sm="12" :md="6">
              <div class="stat-item">
                <div class="stat-icon" style="background-color: #E6A23C">
                  <i class="el-icon-trophy"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-title">前100名高校</div>
                  <div class="stat-value">{{ statisticsData.top100Count }}</div>
                </div>
              </div>
            </el-col>
            <el-col :sm="12" :md="6">
              <div class="stat-item">
                <div class="stat-icon" style="background-color: #F56C6C">
                  <i class="el-icon-user"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-title">平均人数</div>
                  <div class="stat-value">{{ statisticsData.avgPersonCount }}</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 城市分布图 -->
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="card-header">
            <span><i class="el-icon-pie-chart"></i> 高校城市分布</span>
          </div>
          <div id="cityPieChart" class="chart"></div>
        </el-card>
      </el-col>
      
      <!-- 排名分布图 -->
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="card-header">
            <span><i class="el-icon-data-line"></i> 高校排名分布</span>
          </div>
          <div id="rankingBarChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 人数分布图 -->
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="card-header">
            <span><i class="el-icon-data-board"></i> 排名与人数关系图</span>
          </div>
          <div id="scatterChart" class="chart scatter-chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 历年变化趋势 -->
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="card-header">
            <span><i class="el-icon-data-line"></i> 城市高校数量对比</span>
            <el-select
              v-model="selectedCities"
              multiple
              collapse-tags
              placeholder="请选择城市"
              style="width: 350px"
              size="small"
              @change="updateCityComparisonChart"
            >
              <el-option
                v-for="item in cityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div id="cityComparisonChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listCollege } from "@/api/entrance/college";
import * as echarts from 'echarts';

export default {
  name: "CollegeAnalysis",
  data() {
    return {
      loading: false,
      queryParams: {
        city: undefined,
        rankingRange: undefined
      },
      rankingOptions: [
        { value: '1-50', label: '前50名' },
        { value: '51-100', label: '51-100名' },
        { value: '101-200', label: '101-200名' },
        { value: '201-300', label: '201-300名' },
        { value: '301+', label: '300名以后' }
      ],
      collegeList: [],
      statisticsData: {
        totalCount: 0,
        cityCount: 0,
        top100Count: 0,
        avgPersonCount: 0
      },
      cityOptions: [],
      selectedCities: [],
      // 图表实例
      cityPieChart: null,
      rankingBarChart: null,
      scatterChart: null,
      cityComparisonChart: null
    };
  },
  created() {
    this.getCollegeData();
  },
  mounted() {
    this.initCharts();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    // 释放图表资源
    if (this.cityPieChart) this.cityPieChart.dispose();
    if (this.rankingBarChart) this.rankingBarChart.dispose();
    if (this.scatterChart) this.scatterChart.dispose();
    if (this.cityComparisonChart) this.cityComparisonChart.dispose();
  },
  methods: {
    // 获取院校数据
    getCollegeData() {
      this.loading = true;
      
      // 确保能获取所有数据，设置较大的页面大小
      const params = {
        ...this.queryParams,
        pageSize: 1000, // 设置足够大的页面大小以获取所有数据
        pageNum: 1
      };
      
      // 调试信息
      console.log('查询参数:', params);
      
      listCollege(params).then(
        response => {
          this.collegeList = response.rows;
          this.loading = false;
          
          // 调试信息
          console.log('获取到院校数据条数:', this.collegeList.length);
          
          this.calculateStatistics();
          this.updateCharts();
          this.generateCityOptions();
        }
      ).catch(() => {
        this.loading = false;
        this.$message.error("获取院校数据失败");
      });
    },
    
    // 计算统计数据
    calculateStatistics() {
      // 院校总数
      this.statisticsData.totalCount = this.collegeList.length;
      
      // 计算城市数量
      const citySet = new Set();
      this.collegeList.forEach(college => {
        if (college.city) {
          citySet.add(college.city);
        }
      });
      this.statisticsData.cityCount = citySet.size;
      
      // 计算TOP100院校数量
      this.statisticsData.top100Count = this.collegeList.filter(
        college => college.ranking && college.ranking <= 100
      ).length;
      
      // 计算平均人数
      const collegesWithPersonCount = this.collegeList.filter(
        college => college.personCount
      );
      if (collegesWithPersonCount.length > 0) {
        const totalPersonCount = collegesWithPersonCount.reduce(
          (sum, college) => sum + college.personCount, 0
        );
        this.statisticsData.avgPersonCount = Math.round(
          totalPersonCount / collegesWithPersonCount.length
        );
      } else {
        this.statisticsData.avgPersonCount = 0;
      }
    },
    
    // 生成城市选项
    generateCityOptions() {
      const cityMap = {};
      this.collegeList.forEach(college => {
        if (college.city) {
          if (cityMap[college.city]) {
            cityMap[college.city]++;
          } else {
            cityMap[college.city] = 1;
          }
        }
      });
      
      this.cityOptions = Object.keys(cityMap)
        .map(city => ({ value: city, label: `${city} (${cityMap[city]})` }))
        .sort((a, b) => {
          // 根据院校数量降序排序
          const countA = parseInt(a.label.match(/\((\d+)\)/)[1]);
          const countB = parseInt(b.label.match(/\((\d+)\)/)[1]);
          return countB - countA;
        });
      
      // 默认选择前5个城市
      this.selectedCities = this.cityOptions.slice(0, 5).map(option => option.value);
    },
    
    // 初始化图表
    initCharts() {
      this.$nextTick(() => {
        // 初始化城市分布饼图
        const cityPieChartDom = document.getElementById('cityPieChart');
        if (cityPieChartDom) {
          this.cityPieChart = echarts.init(cityPieChartDom);
        }
        
        // 初始化排名分布柱状图
        const rankingBarChartDom = document.getElementById('rankingBarChart');
        if (rankingBarChartDom) {
          this.rankingBarChart = echarts.init(rankingBarChartDom);
        }
        
        // 初始化排名-人数散点图
        const scatterChartDom = document.getElementById('scatterChart');
        if (scatterChartDom) {
          this.scatterChart = echarts.init(scatterChartDom);
        }
        
        // 初始化城市对比图
        const cityComparisonChartDom = document.getElementById('cityComparisonChart');
        if (cityComparisonChartDom) {
          this.cityComparisonChart = echarts.init(cityComparisonChartDom);
        }
        
        // 添加窗口大小变化监听
        window.addEventListener('resize', this.resizeCharts);
        
        // 更新图表
        this.updateCharts();
      });
    },
    
    // 调整图表大小
    resizeCharts() {
      if (this.cityPieChart) this.cityPieChart.resize();
      if (this.rankingBarChart) this.rankingBarChart.resize();
      if (this.scatterChart) this.scatterChart.resize();
      if (this.cityComparisonChart) this.cityComparisonChart.resize();
    },
    
    // 更新所有图表
    updateCharts() {
      if (!this.collegeList || this.collegeList.length === 0) return;
      
      this.updateCityPieChart();
      this.updateRankingBarChart();
      this.updateScatterChart();
      this.updateCityComparisonChart();
    },
    
    // 更新城市分布饼图
    updateCityPieChart() {
      if (!this.cityPieChart) return;
      
      // 统计城市分布数据
      const cityMap = {};
      this.collegeList.forEach(item => {
        if (item.city) {
          if (cityMap[item.city]) {
            cityMap[item.city]++;
          } else {
            cityMap[item.city] = 1;
          }
        }
      });
      
      // 转换为图表数据格式
      const data = Object.keys(cityMap).map(city => ({
        name: city,
        value: cityMap[city]
      }));
      
      // 排序并截取前10个城市，剩余的归为"其他"
      data.sort((a, b) => b.value - a.value);
      let topCities = data.slice(0, 10);
      
      // 如果有超过10个城市，将剩余的归为"其他"
      if (data.length > 10) {
        const otherCount = data.slice(10).reduce((sum, item) => sum + item.value, 0);
        topCities.push({
          name: '其他城市',
          value: otherCount
        });
      }
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 20,
          bottom: 20,
          data: topCities.map(item => item.name)
        },
        series: [
          {
            name: '城市分布',
            type: 'pie',
            radius: '55%',
            center: ['40%', '50%'],
            data: topCities,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              formatter: '{b}: {c} ({d}%)'
            }
          }
        ]
      };
      
      this.cityPieChart.setOption(option);
    },
    
    // 更新排名分布柱状图
    updateRankingBarChart() {
      if (!this.rankingBarChart) return;
      
      // 定义排名区间
      const rankingRanges = [
        { name: '前50名', min: 1, max: 50, count: 0 },
        { name: '51-100名', min: 51, max: 100, count: 0 },
        { name: '101-200名', min: 101, max: 200, count: 0 },
        { name: '201-300名', min: 201, max: 300, count: 0 },
        { name: '300名以后', min: 301, max: Infinity, count: 0 },
        { name: '未排名', min: 0, max: 0, count: 0 }
      ];
      
      // 调试信息
      console.log('分析页院校总数:', this.collegeList.length);
      
      // 统计排名分布
      this.collegeList.forEach(item => {
        if (!item.ranking) {
          rankingRanges[5].count++; // 未排名
        } else if (item.ranking <= 50) {
          rankingRanges[0].count++; // 前50名
        } else if (item.ranking <= 100) {
          rankingRanges[1].count++; // 51-100名
        } else if (item.ranking <= 200) {
          rankingRanges[2].count++; // 101-200名
        } else if (item.ranking <= 300) {
          rankingRanges[3].count++; // 201-300名
        } else {
          rankingRanges[4].count++; // 300名以后
        }
      });
      
      // 调试信息
      console.log('分析页排名分布统计:', rankingRanges);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: rankingRanges.map(item => item.name)
        },
        yAxis: {
          type: 'value',
          name: '院校数量'
        },
        series: [
          {
            name: '院校数量',
            type: 'bar',
            data: rankingRanges.map(item => ({
              value: item.count,
              itemStyle: {
                color: this.getRankingBarColor(item.name)
              }
            })),
            label: {
              show: true,
              position: 'top'
            }
          }
        ]
      };
      
      this.rankingBarChart.setOption(option);
    },
    
    // 更新散点图
    updateScatterChart() {
      if (!this.scatterChart) return;
      
      // 准备散点图数据（排名和人数的关系）
      const scatterData = this.collegeList
        .filter(item => item.ranking && item.personCount)
        .map(item => [
          item.ranking,
          item.personCount,
          item.collegeName,
          item.city || '未知'
        ]);
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            return '院校: ' + params.data[2] + '<br/>' +
                   '排名: ' + params.data[0] + '<br/>' +
                   '人数: ' + params.data[1] + '<br/>' +
                   '城市: ' + params.data[3];
          }
        },
        grid: {
          left: '3%',
          right: '7%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '排名',
          nameLocation: 'middle',
          nameGap: 30,
          scale: true,
          axisLabel: {
            formatter: '{value}'
          }
        },
        yAxis: {
          type: 'value',
          name: '人数',
          scale: true
        },
        series: [
          {
            name: '排名与人数',
            type: 'scatter',
            symbolSize: function (data) {
              // 根据排名调整点的大小，排名越高点越大
              return Math.max(10, 30 - data[0] / 20);
            },
            data: scatterData,
            itemStyle: {
              color: function(params) {
                // 根据排名设置颜色
                const ranking = params.data[0];
                if (ranking <= 50) return '#F56C6C';
                if (ranking <= 100) return '#E6A23C';
                if (ranking <= 200) return '#67C23A';
                return '#409EFF';
              }
            }
          }
        ]
      };
      
      this.scatterChart.setOption(option);
    },
    
    // 更新城市对比图
    updateCityComparisonChart() {
      if (!this.cityComparisonChart || !this.selectedCities || this.selectedCities.length === 0) return;
      
      // 准备城市数据
      const categories = ['前50名', '51-100名', '101-200名', '201-300名', '300名以后', '未排名'];
      const series = [];
      
      // 为每个选中的城市生成数据
      this.selectedCities.forEach(city => {
        // 筛选该城市的院校
        const cityColleges = this.collegeList.filter(
          college => college.city === city
        );
        
        // 统计各个排名区间的数量
        const rankingCounts = [0, 0, 0, 0, 0, 0]; // 对应六个排名区间
        
        cityColleges.forEach(college => {
          if (!college.ranking) {
            rankingCounts[5]++; // 未排名
          } else if (college.ranking <= 50) {
            rankingCounts[0]++; // 前50名
          } else if (college.ranking <= 100) {
            rankingCounts[1]++; // 51-100名
          } else if (college.ranking <= 200) {
            rankingCounts[2]++; // 101-200名
          } else if (college.ranking <= 300) {
            rankingCounts[3]++; // 201-300名
          } else {
            rankingCounts[4]++; // 300名以后
          }
        });
        
        // 调试信息
        console.log(`城市 ${city} 排名分布:`, rankingCounts);
        
        series.push({
          name: city,
          type: 'bar',
          data: rankingCounts,
          label: {
            show: true,
            position: 'inside',
            formatter: function(params) {
              return params.value > 0 ? params.value : '';
            }
          }
        });
      });
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: this.selectedCities
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: categories
        },
        yAxis: {
          type: 'value',
          name: '院校数量'
        },
        series: series
      };
      
      this.cityComparisonChart.setOption(option);
    },
    
    // 根据排名获取柱状图颜色
    getRankingBarColor(rankName) {
      const colorMap = {
        '前50名': '#F56C6C',
        '51-100名': '#E6A23C',
        '101-200名': '#67C23A',
        '201-300名': '#409EFF',
        '300名以后': '#909399',
        '未排名': '#DCDFE6'
      };
      return colorMap[rankName] || '#409EFF';
    },
    
    // 搜索过滤
    handleFilter() {
      this.getCollegeData();
    },
    
    // 重置过滤
    resetFilter() {
      this.queryParams = {
        city: undefined,
        rankingRange: undefined
      };
      this.getCollegeData();
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .filter-container {
    margin-bottom: 20px;
  }
  
  .statistics-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      align-items: center;
      
      i {
        margin-right: 5px;
        color: #409EFF;
      }
    }
    
    .stat-item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      padding: 15px;
      border-radius: 5px;
      background-color: #f9f9f9;
      
      .stat-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 60px;
        height: 60px;
        border-radius: 50%;
        margin-right: 15px;
        
        i {
          font-size: 24px;
          color: #fff;
        }
      }
      
      .stat-info {
        .stat-title {
          font-size: 14px;
          color: #606266;
          margin-bottom: 5px;
        }
        
        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
        }
      }
    }
  }
  
  .chart-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      span {
        font-size: 16px;
        font-weight: bold;
        
        i {
          margin-right: 5px;
          color: #409EFF;
        }
      }
    }
    
    .chart {
      height: 350px;
      
      &.scatter-chart {
        height: 450px;
      }
    }
  }
}
</style> 